package com.lm.paymentadmin.common.filter;

import com.alibaba.fastjson.JSON;
import com.lm.paymentadmin.common.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求拦截器
 * swagger2文档不拦截
 * 登录注册不拦截
 * 注册发送验证码不拦截
 * oos不拦截
 * @author liu2dog
 */
@Slf4j
@WebFilter(filterName = "tokenFilter",urlPatterns = {"/*"})
@CrossOrigin
public class HttpTokenFilter implements Filter {
    @Resource
    private JwtUtils jwtUtils;


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;

        //防止预请求被拦截
        if (HttpMethod.OPTIONS.toString().equals(httpRequest.getMethod())) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        StringBuffer url=httpRequest.getRequestURL();
        if (httpRequest.getRequestURL().indexOf("login/account") != -1
                ||httpRequest.getRequestURL().indexOf("login/email") != -1
                ||httpRequest.getRequestURL().indexOf("test/") != -1
                ||httpRequest.getRequestURL().indexOf("user/sendEmail") != -1
                ||httpRequest.getRequestURL().indexOf("user/registeredUser") != -1
            ||httpRequest.getRequestURL().indexOf("common/uploadOSS") != -1
            ||httpRequest.getRequestURL().indexOf("common/deleteOSS") != -1
                ||httpRequest.getRequestURL().indexOf(".html") != -1
                ||httpRequest.getRequestURL().indexOf(".css") != -1
                ||httpRequest.getRequestURL().indexOf(".js") != -1
                ||httpRequest.getRequestURL().indexOf(".ico") != -1
                ||httpRequest.getRequestURL().indexOf("swagger") != -1
                ||httpRequest.getRequestURL().indexOf("api-") != -1) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String auth = httpRequest.getHeader("Authorization");
        if ((auth != null) && (auth.length() > 7)) {
            Claims claims = jwtUtils.getClaimByToken(auth);
            if (claims != null) {
                log.info("\nurl:{}\nparams:{}\nusername:{}",url, JSON.toJSONString(httpRequest.getParameterMap()),claims.get("username"));
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
